import os

from eval_lib.common.logger import get_logger
from common.module import AgentMeta, DFServerMeta
from config import conf
from common import const
from platform_tools.aliyun.aliyun_sdk import Aliyun
from platform_tools.base import PlatformBase
from agent_tools.deepflow_agent.deepflow_agent import DeeepflowAgent
from agent_tools.base import AgentBase
from deploy.dfenvs import DFEnvs

log = get_logger()


class ParseConfig():

    @staticmethod
    def choose_platform() -> PlatformBase:
        platform_type = conf.platform_tools.get("type", "")
        if platform_type == 'aliyun':
            aliyun_info = conf.platform_tools.get("aliyun", {})
            if 'ALICLOUD_ACCESS_KEY' not in os.environ:
                os.environ['ALICLOUD_ACCESS_KEY'] = aliyun_info['access_key']

            if 'ALICLOUD_SECRET_KEY' not in os.environ:
                os.environ['ALICLOUD_SECRET_KEY'] = aliyun_info['secret_key']

            if 'ALICLOUD_REGION' not in os.environ:
                os.environ['ALICLOUD_REGION'] = aliyun_info['region']
            return Aliyun
        else:
            # 如果没有选择有效的平台，则记录错误并返回 None
            log.error("Invalid platform type specified.")
            return None

    @staticmethod
    def choose_agent() -> AgentBase:
        agent_type = conf.case_params.agent_type
        if agent_type == 'deepflowce':
            return DeeepflowAgent
        else:
            # 如果没有选择有效的 agent，则记录错误并返回 None
            log.error("Invalid agent type specified.")
            assert False

    @staticmethod
    def get_agent_meta_data(agent_ip):
        agent_type = conf.case_params.agent_type
        agent_conf = conf.agent_tools.get(agent_type)
        agent_version = agent_conf['version']
        agent_meta = AgentMeta()
        agent_meta.ssh_port = conf.runner_ssh_port
        agent_meta.ssh_password = conf.runner_ssh_password
        agent_meta.ssh_username = conf.runner_ssh_username
        agent_meta.agent_ip = agent_ip
        agent_meta.version = agent_version
        return agent_meta

    @staticmethod
    def create_redis_client_df_envs() -> DFEnvs:
        return DFEnvs(conf.case_params.uuid)

    @staticmethod
    def get_df_server_meta(case_type) -> DFServerMeta:
        if case_type is None:
            log.error("case type is none")
            assert False
        server_meta = DFServerMeta()
        agent_type = conf.case_params.agent_type
        platform_type = conf.platform_tools.get("type", "")
        if platform_type:
            if agent_type == 'deepflowce':
                redis_df_envs = ParseConfig.create_redis_client_df_envs()
                if case_type == const.CASE_TYPE_CONCURRENCY:
                    df_env_info = redis_df_envs.get_concurrency_df_env()
                elif case_type == const.CASE_TYPE_MONOPOLIZE:
                    df_env_info = redis_df_envs.get_monopolize_df_env()
                if not df_env_info:
                    log.error("get df env info failed")
                    assert False
                server_meta.ssh_port = conf.runner_ssh_port
                server_meta.ssh_password = conf.runner_ssh_password
                server_meta.ssh_username = conf.runner_ssh_username
                server_meta.server_ip = df_env_info["mgt_ip"]
                server_meta.control_port = df_env_info[
                    "server_controller_port"]
                server_meta.query_port = df_env_info["server_query_port"]
        else:
            if agent_type == 'deepflowce':
                agent_param = conf.agent_tools[agent_type]
                server_meta.ssh_port = agent_param["server_ssh_port"]
                server_meta.ssh_password = agent_param["server_ssh_password"]
                server_meta.ssh_username = agent_param["server_ssh_username"]
                server_meta.server_ip = agent_param["server_ip"]
                server_meta.control_port = None
                server_meta.query_port = None
        if not server_meta.server_ip:
            log.error("get server ip failed")
            assert False
        return server_meta

    @staticmethod
    def release_df_env(server_ip):
        agent_type = conf.case_params.agent_type
        platform_type = conf.platform_tools.get("type", "")
        if platform_type:
            if agent_type == 'deepflowce':
                redis_df_envs = ParseConfig.create_redis_client_df_envs()
                redis_df_envs.release_df_env(server_ip)
        else:
            if agent_type == 'deepflowce':
                return

    @staticmethod
    def get_fixed_host_ip(instance_name: str):
        host_info: dict = conf.fixed_host
        index = instance_name.rfind("-")
        ip = ""
        if instance_name[:index] in host_info.keys():
            ip = host_info[instance_name[:index]]
        else:
            log.error("fixed host ip not found")
            assert False
        return ip

    @staticmethod
    def get_case_short_uuid():
        return conf.case_params.uuid[:8]
